import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const user = ref(JSON.parse(localStorage.getItem('user') || '{}'))
  
  const isLoggedIn = computed(() => !!token.value)
  
  // 登录
  async function login(username, password) {
    try {
      const response = await axios.post('/api/v1/login', { username, password })
      
      if (response.data.code === 0) {
        const { token: newToken, user: userData } = response.data.data
        
        token.value = newToken
        user.value = userData
        
        localStorage.setItem('token', newToken)
        localStorage.setItem('user', JSON.stringify(userData))
        
        // 设置axios默认请求头
        axios.defaults.headers.common['Authorization'] = `Bearer ${newToken}`
        
        return { success: true }
      } else {
        return { success: false, message: response.data.message || '登录失败' }
      }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, message: error.response?.data?.message || '登录失败，请稍后再试' }
    }
  }
  
  // 登出
  function logout() {
    token.value = ''
    user.value = {}
    
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    
    // 清除axios默认请求头
    delete axios.defaults.headers.common['Authorization']
  }
  
  // 获取用户信息
  async function getUserInfo() {
    try {
      const response = await axios.get('/api/v1/user/info')
      
      if (response.data.code === 0) {
        user.value = response.data.data
        localStorage.setItem('user', JSON.stringify(response.data.data))
        return { success: true }
      } else {
        return { success: false, message: response.data.message || '获取用户信息失败' }
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return { success: false, message: error.response?.data?.message || '获取用户信息失败，请稍后再试' }
    }
  }
  
  return { token, user, isLoggedIn, login, logout, getUserInfo }
}) 